from os.path import join

import numpy as np
import cv2
import os

path = os.path.abspath('.')
path = join(path, '2.jpg')


def showSize(img, size):
    x = img.shape[0]
    y = img.shape[1]

    if x > size or y > size:
        mul_x = x // size
        mul_y = y // size
        if mul_x > mul_y:
            mul = mul_x + 1
        else:
            mul = mul_y + 1
    else:
        mul = 1
    width = y // mul
    height = x // mul
    return width, height


def showLine(inimg):
    # img = cv2.resize(inimg,None,fx=0.8,fy=0.8,interpolation=cv2.INTER_CUBIC)

    scr = inimg
    img = cv2.cvtColor(scr, cv2.COLOR_BGR2GRAY)
    img = cv2.GaussianBlur(img, (3, 3), 0)
    edges = cv2.Canny(img, 20, 80, apertureSize=3)

    lines = cv2.HoughLines(edges, 1, np.pi / 180, 118)
    result = edges.copy()

    # minLineLength = 300
    # maxLineGap = 50
    # lines = cv2.HoughLinesP(edges, 1, np.pi / 180, 10, minLineLength, maxLineGap)
    # for l in lines.tolist():
    #     x1,y1,x2,y2 = l[0]
    #     cv2.line(scr, (x1, y1), (x2, y2), (0, 255, 0), 20)

    for line in lines:
        rho = line[0][0]
        theta = line[0][1]
        print('rho=', rho, '-----theta=', theta)
        if (theta < (np.pi / 4.0)) or (theta > (3.0 * np.pi / 4.0)):
            pt1 = (int(rho / np.cos(theta)), 0)
            pt2 = (int((rho-result.shape[0]*np.sin(theta))/np.cos(theta)),result.shape[0])
            cv2.line(result, pt1, pt2, (255))
        else:
            pt1 = (int(rho / np.sin(theta)), 0)
            pt2 = (result.shape[1], int((rho-result.shape[1]*np.cos(theta))/np.sin(theta)))
            cv2.line(result, pt1, pt2, (255))
    return scr, result


if __name__ == '__main__':
    img = cv2.imread(path)
    size = showSize(img, 600)
    scr, result = showLine(img)
    scr = cv2.resize(scr, size)
    result = cv2.resize(result, size)
    cv2.imshow('1', scr)
    cv2.imshow('2', result)

    cv2.waitKey(0)
    cv2.destroyAllWindows()
